function entrain()
%
% compute spike entrainment from selected data set.
%
%try
    sf = getmainselection;
    if(sf > 0) 
        pflag = getplotflag;
        QueMessage('Entrainment analysis', 1); % clear the que
        for i = 1:length(sf)
            entrain_2(sf(i), pflag);
        end;
    end;
    return;
   %catch
    watchoff;
    QueMessage('Error in Entrain Analysis routine', 1);
    %end;


function entrain_2(sf, plot_flag)

global VOLTAGE CURRENT DFILE

global CONTROL

QueMessage('Entrain - Starting');
[DFILE, err] = analysis_setup(DFILE, sf);

if(err ~= 0)
    return;
end;

spike_thresh=number_arg(CONTROL(sf).thresh);
QueMessage(sprintf('Entrain - Spike Threshold = %7.2f mV', spike_thresh));
protocol=deblank(lower(CONTROL(sf).protocol));


% we go through the data, with a different measure of spike latency for EACH stimulus.
    lat  = 20;
    ipi = 5;
    ns = 10;
    ans = inputdlg({'Nstim', 'Interpulse interval (ms)', 'First pulse latency (ms)', 'Min Latency (ms)'}, 'Entrainment Analysis Parameters', ...
        1, {'10', '10', '20', '1.0'});
    ns = str2num(ans{1});
    ipi = str2num(ans{2});
    lat = str2num(ans{3});
    minlat = str2num(ans{4});
    steps = lat + [0:ns-1]*ipi;
    DFILE.steps = steps;

ipi = mean(diff(DFILE.steps)); % get interpulse interval

nstim = length(DFILE.steps);
for i = 1:nstim
    f = find_spikes(DFILE, DFILE.steps(i)+minlat, DFILE.steps(i)+ipi+minlat, spike_thresh); % for each STEP, all records
    fsl{i} = f;
end;
for i = 1:nstim
    [mfsl(i) sfsl(i)] = mean_var(fsl{i});
ntrial = length(fsl{i});
    k = find(isnan(fsl{i}));
    p(i) = (ntrial - length(k))/ntrial;
end;
[mfsl+minlat; sfsl; p]'

% generate the figure...
h = findobj('tag', 'datac_entrain');
if(isempty(h) | ~ishandle(h))
    h = figure('tag', 'datac_entrain');
else
    figure(h);
    clf;
end;
figure (h);
subplot('Position', [0.1,0.85,0.7,0.1]);
   axis([0,1,0,1])
   axis('off')
   text(0,0.8126,sprintf('%-12s R[%d:%d] %-8s',DFILE.filename, DFILE.frec, DFILE.lrec, CONTROL(sf).protocol), 'Fontsize', 8);
   text(0,0.675,sprintf('Solution:%-12s  gain:%4.1f  LPF:%4.1f kHz', CONTROL(sf).solution, DFILE.igain, DFILE.low_pass(1)), 'FontSize', 7);
   text(0.0.5,sprintf('%s',date),'FontSize',7);

  subplot('Position', [0.1, 0.4, 0.3, 0.7]);
  nt = [1:length(mfsl)];
  plot(nt, mfsl+minlat, 's');
  errorbar(nt, mfsl+minlat, sfsl, '-');
  xlabel('stimulus number');
  ylabel('Latency (ms)');
  
  % lower plot
   subplot('Position', [0.1, 0.1, 0.3, 0.7]);
    plot(nt, p);
    xlabel('stimulus number');
    ylabel ('P(spike');
    
   
